import datetime
import json
from django.shortcuts import render, redirect
from django.http import JsonResponse
from app import models
from django.views.decorators.csrf import csrf_exempt
from app.models import Dwy

# @csrf_exempt
# def dwy(request):
#     if request.method == 'GET':
#         sensor = int(request.GET.get('sensor'))
#         sensors = list(range(1, sensor + 1))
#         ddg = int(request.GET.get('ddg'))
#         ddgs = list(range(1, ddg + 1))
#         date = str(datetime.date.today())
#         count = models.Dwy.objects.filter(date=date, type='DWY').count()  # 当天的最大数量

#         A1PH_Received02 = request.unicom_username + '-' + str(count) + '-' + date + "-DWY"
#         return render(request, 'DWY/DWY.html',
#                       {'sensors': sensors, 'sensor': sensor, 'ddgs': ddgs, 'ddg': ddg,
#                        'A1PH_Received02': A1PH_Received02, 'date': date,
#                        'windows_user': request.unicom_full_name})

#     # 把前端获得的数据保存到数据库以json字典的形式，方便前端调用
#     all_data = {}
#     # 获得前端所有字段的key值也就是名字
#     all_field_names = request.POST.keys()
#     # 循环获得所有的值，如果列表中是单个值就直接赋值给key，如果是列表保持不变
#     for field_name in all_field_names:
#         value_list = request.POST.getlist(field_name)
#         if len(value_list) == 1:
#             all_data[field_name] = value_list[0]
#         else:
#             all_data[field_name] = value_list
#     # 向Ddy数据库写入数据
#     ddy_data = Dwy(all_data=all_data, c_number=request.POST.get('A1PH_Received02'), date=request.POST.get('A1PH_Rq07'),
#                    customer=request.POST.get('A1PH_Zsdw53'),
#                    snr=request.POST.get('A1PH_SN04'), type='DWY', user=request.unicom_username)
#     ddy_data.save()
#     return redirect('/list/')

#新
# ... existing code ...
@csrf_exempt
def dwy(request):
    if request.method == 'GET':
        sensor = int(request.GET.get('sensor'))
        sensors = list(range(1, sensor + 1))
        ddg = int(request.GET.get('ddg'))
        ddgs = list(range(1, ddg + 1))
        date = str(datetime.date.today())
        short_date = datetime.date.today().strftime('%m%d%y')
        year = datetime.date.today().strftime('%Y')
        count = models.Dwy.objects.filter(date__startswith=year, type='DWY', user=request.unicom_username).count() + 1

        A1PH_Received02 = request.unicom_username + '-' + f"{count:03d}" + '-' + short_date + "-DWY"
        
        # 获取工具信息用于下拉选择框
        tools = models.ToolInfo.objects.filter(type=3)
        
        return render(request, 'DWY/DWY.html',
                      {'sensors': sensors, 'sensor': sensor, 'ddgs': ddgs, 'ddg': ddg,
                       'A1PH_Received02': A1PH_Received02, 'date': date,
                       'windows_user': request.unicom_full_name, 'tools': tools})

    # 处理前端发送的JSON数据
    # ... existing code ...

    """公共函数：处理表单保存的公共逻辑"""
    data = request.POST.dict()
    form_data = Dwy(
        all_data=data,
        c_number=request.POST.get('A1PH_Received02'),
        date=request.POST.get('A1PH_Rq07'),
        customer=request.POST.get('A1PH_Zsdw53'),
        snr=request.POST.get('A1PH_SN04'),
        user=request.unicom_username,
        type='DWY'
    )
    form_data.save()
    return redirect('/list/')


def ddg(request):
    selected_value = request.GET.get('value')
    if selected_value == '10':
        data_list = [2, 4, 6, 8, 10]
        return JsonResponse({'datalist': data_list})

    if selected_value == '20':
        data_list = [1, 5, 10, 20]
        return JsonResponse({'datalist': data_list})
